/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
import { ExceptionFilter, Catch, ArgumentsHost, HttpException, Logger, HttpStatus } from '@nestjs/common';
import { Request, Response } from 'express';
import { isString } from '@src/utils';
import { ObjectType } from '@src/types';

@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();

    const status = exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;
    const message = exception.message || null;
    Logger.error(JSON.stringify(exception), "错误日志", 'HttpExceptionFilter');
    const _error = status == 500 ? '异常' : this.toResult(exception.getResponse() || '');
    const msg = {
      code: status,
      timestamp: new Date().toISOString(),
      path: request.url,
      method: request.method,
      message: message || '请求失败',
      data: _error
    };
    response.status(status)
      .json(msg);
  }

  public toResult(resp: string | ObjectType): string {
    if (isString(resp)) {
      return resp.toString()
    } else {
      const str = []
      for (const key in new Object(resp)) {
        str.push(key + ':' + resp[key])
      }
      return str.join(',')
    }
  }
}
